﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace RTS_WebServer
{
    class RTSResponse
    {
        public int Status;
        public string StatusText;
        public Stream response;
        Dictionary<string, string> Headers = new Dictionary<string, string>();
        public RTSResponse(RTSRequest Quest)
            : base()
        {
            string filepath = Program.Configuration["path"] + Quest.Path;
            if (File.Exists(filepath))
            {
                Headers.Add("Content-Length", (new FileInfo(filepath)).Length.ToString());
                response = File.OpenRead(filepath);
            }
            else if (Directory.Exists(filepath))
            {
                int i = 0;
                string found = null;
                string[] indexes = Program.Configuration["indexfiles"].Split(new char[] { ';' });
                while (i < indexes.Length && found == null)
                {
                    Status = 200;
                    StatusText = "OK";
                    string f = filepath + "\\" + indexes[i];
                    if (File.Exists(f)) found = f;
                }
                if (found == null)
                {
                    Status = 404;
                    StatusText = "I can't find it :'(";
                }
                else
                {
                    Status = 200;
                    StatusText = "OK";
                    Headers.Add("Content-Length", (new FileInfo(found)).Length.ToString());
                    response = File.OpenRead(found);
                }
            }
            else
            {
                Status = 404;
                StatusText = "I can't find it :'(";
            }
        }
        public void Answer(Stream flood)
        {
            string head = "HTTP/1.1 " + Status.ToString() + " " + StatusText + "\r\n";
            foreach (KeyValuePair<string, string> KV in Headers)
            {
                head += KV.Key.Trim() + ": " + KV.Value + "\r\n";
            }
            head += "\r\n";
            byte[] bytehead = Encoding.ASCII.GetBytes(head);
            flood.Write(bytehead, 0, bytehead.Length);
            if (response != null)
            {
                if (response.GetType() == typeof(FileStream))
                {

                        try
                        {
                            StreamExtensions.CopyTo(response, flood);
                        }catch(Exception ex){
                           
                        }
                    }
                }
            }

        }
    }
